/* eslint-disable */
import {
  registerMicroApps,
  setDefaultMountApp,
  start,
  initGlobalState,
  prefetchApps,
} from 'qiankun'
import type { RegisterApplicationConfig } from 'single-spa'
import { appAction, onGlobalStateChange, dispatchAction } from '@/app.action'
import { microAppName } from '@/global-config/resource'
import { Actions, DEV_SYSTEM_CONF_MAP } from '@/app.constants'
import * as appTypes from '@/store/modules/App/types'
import { store } from '@/store'

export const getActiveRule = (
  activity: string | RegisterApplicationConfig['activeWhen']
) => {
  if (typeof activity === 'string') {
    return (location: Location) => {
      const { pathname, hash } = location
      /**
       * 此处用 location.pathname.endsWith(activity) 判断，会导致切换页面的时候子应用 unmount
       * 原因: 此处的 pathname 可能出现未知情况导致 获取错误
       * 1. 正确：/static/aaaa/micro-app/#/student/ty-selection-period
       * 2. 错误：/static/aaaa/student/ty-selection-period"
       */
      return pathname.includes(activity) || hash.includes(activity)
    }
  } else {
    return activity
  }
}

/**
 * @name 启用qiankun微前端应用
 * @param {Array} list 应用注册表信息
 */
export const qianKunStart = async (subApps: any[]) => {
  /**
   * @name 处理子应用注册表数据
   */
  let apps: any[] = []
  let defaultApp!: any // 默认注册应用路由前缀
  let manualPrefetchAppsList: any[] = []
  let corsAppsList: any[] = [] // 跨域的app

  subApps.forEach((app) => {
    const { routerBase, entry, name, container, sysId } = app as Required<any>
  })
  console.log('qiankun开始启动')
  apps.push({
    name: microAppName['car-team'], // app name registered
    entry: DEV_SYSTEM_CONF_MAP[1].entry,
    container: '#micro-app',
    activeRule: getActiveRule('#/car-team'),
  })
  console.log(apps)
  /**
   * @name 注册子应用
   * @param {Array} list subApps
   */
  registerMicroApps(apps, {
    beforeLoad: [
      async () => {
        store.commit(
          `${appTypes.MODULE_NAME}/${appTypes.UPDATE_SUB_APP_LOADING}`,
          true
        )
      },
    ],
    afterMount: [
      async () => {
        // 传递主系统共享数据
        // dispatchAction({
        //   action: Actions.DISPENSE_SHARED_DATA,
        //   value: {
        //   },
        // });
        // 传递主系统用户信息
        console.log('qiankun启动完毕')
        const { account: { enterpriseId, departmentId, openId, roleId, accessToken } } = store.state as Record<string, any>
        dispatchAction({
          action: Actions.DISPENSE_USER_INFO,
          value: {
            appId: store.state.appId,
            enterpriseId,
            departmentId,
            openId,
            roleId,
            Authorization: accessToken ? `Bearer ${accessToken}` : ''
          }
        })
      },
      async (app) => {
        store.commit(
            `${appTypes.MODULE_NAME}/${appTypes.SET_CURRENT_SUB_APP}`,
            app
        )
      },
      async () => {
        store.commit(
          `${appTypes.MODULE_NAME}/${appTypes.UPDATE_SUB_APP_LOADING}`,
          false
        )
      }
    ],
    afterUnmount: [
    ],
  })

  /**
   * @name 设置默认进入的子应用
   * @param {String} 需要进入的子应用路由前缀
   */
  // if (!!defaultApp) setDefaultMountApp(defaultApp?.defaultAppLink ?? '/')

  /**
   * 设置预加载子应用
   */

  /**
   * @name 启动微前端
   */
  start({
    prefetch: 'all', // 预加载
    sandbox: {
      // [issue](https://github.com/umijs/qiankun/pull/1061)
      // strictStyleIslation: true, // 开启该项 experimentalStyleIsolation 无效
      experimentalStyleIsolation: true,
    },
    fetch(url: string, ...args: any[]) {
      const corsDomain = corsAppsList.map((app) => {
        return app.entry
      })
      const isCorsDomain = corsDomain.some((domain) =>
        (url as string).includes(domain)
      )
      // 给指定的微应用 entry 开启跨域请求
      if (isCorsDomain) {
        return window.fetch(url, {
          ...args,
          mode: 'cors',
          credentials: 'include',
        })
      }

      return window.fetch(url, ...args)
    }
  })

  /**
   * @name 启动qiankun应用间通信机制
   */
  const action = appAction(initGlobalState)

  return {
    action
  }
}
